﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

using RexToy.UI.WinForm.Pmlx;

namespace RexToy.UI.WinForm.ViewModel
{
    public interface IDataExchange
    {
        bool Exchange { get; }
        void UpdateModel(ViewModelBase model);
        void UpdateView(ViewModelBase model);
        string BindPropertyName { get; set; }
        UpdateModelTrigger UpdateModelTrigger { get; set; }
    }

    public static class DataExchangeControlExtension
    {
        private static string GetNameWithoutPrefix(this Control c)
        {
            int idx;
            for (idx = 0; idx < c.Name.Length; idx++)
            {
                if (char.IsLower(c.Name[idx]))
                    continue;
                else
                    break;
            }
            return c.Name.Substring(idx);
        }

        public static string GetBindProperty(this Control c, string propertyName)
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                if (string.IsNullOrEmpty(c.Name))
                    return string.Empty;
                else
                    return c.GetNameWithoutPrefix();
            }
            else
                return propertyName;
        }

        private static IModelOwner GetDataExchangeHost(this Control c)
        {
            Control parent = c.Parent;
            while (parent != null)
            {
                IModelOwner mo = parent as IModelOwner;
                if (mo != null && mo.ViewModel != null)
                    return mo;
                else
                    parent = parent.Parent;
            }
            return null;
        }

        public static void UpdateModelByTrigger(this IDataExchange de, UpdateModelTrigger trigger)
        {
            if (de.UpdateModelTrigger == trigger)
            {
                Control c = de as Control;
                IModelOwner owner = c.GetDataExchangeHost();
                if (owner != null)
                {
                    ViewModelBase vm = owner.ViewModel;
                    de.UpdateModel(vm);
                }
            }
        }
    }
}
